package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = orderService.findPage(queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(), queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/sendMsg")
    public Result sendMsg(@RequestBody Map map) throws Exception {
        Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));
        String code = DateUtils.parseDate2String(orderDate);
        String phoneNumber = (String) map.get("phoneNumber");
        System.out.println(code);
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phoneNumber, code);
            return new Result(true, "短信发送成功");
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, "发送失败");
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Map map, Integer[] setmealIds) {
        Result result = null;
        try {
            map.put("orderType", Order.ORDERTYPE_TELEPHONE);
            result = orderService.add(map, setmealIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            orderService.delete(id);
            return new Result(true, MessageConstant.DELETE_ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ORDER_FAIL);
        }
    }
}
